<?php
/**
 * 示例服务
 * 
 * @author ShuangYa
 * @package APIGateway
 * @category Demo
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2018 ShuangYa
 * @license https://www.sylibs.com/go/apigateway/license
 */
namespace ag\service;

use ag\library\ServiceInterface;

class User implements ServiceInterface {
	public static function getMethods(): array {
		return [
			'get',
			'set',
			'token'
		];
	}
	public static function exists(string $name): bool {
		return in_array($name, self::getMethods(), TRUE);
	}
	public static function call(array $server, string $name, $data) {
		// For example, using HTTP
		$cli = new Swoole\Coroutine\Http\Client($server['address'], $server['port']);
		$cli->setHeaders([
    		'Host' => 'example.com'
		]);
		$cli->set([
			'timeout' => 1
		]);
		$cli->post('/' . $name, $data->serializeToJsonString());
		if ($cli->errCode !== 0) {
			$cli->close();
			return $cli->errCode;
		}
		$result = $cli->body;
		$cli->close();
		// In this case, we using swoole_serialize in user service
		$result = swoole_unserialize($result);
		if ($result['success']) {
			switch ($name) {
				case 'get':
					return new Proto\Api\User\Get\Response($result);
				case 'set':
					return new Proto\Api\User\Set\Response($result);
				case 'token':
					return new Proto\Api\User\Token\Response($result);
			}
		} else {
			return $result['error'];
		}
	}
	public static function getStatus(array $server): int {
		return 1;
	}
}